import router from "@/router";
import { useSession } from "@/stores/sesstion";
import { parseObjectKeyValue, randomStr, showToast, } from "@/utils/utils";

const http = window.http;
http.setInterceptor(async (options, next) => {
    const session = useSession();
    const headers = options.headers || {};
    const nonce = randomStr();
    const timestamp = Date.now();
    headers['Authorization'] = session.token;

    headers['nonce'] = nonce;
    headers['timestamp'] = timestamp;
    headers['x-token'] = await window.api.getDeviceId();
    headers['Content-Type'] = 'application/json;charset=UTF-8';
    const data = options.method == 'GET' ? (options.query || {}) : (options.body || {});
    const dataStr = Object.keys(data).length > 0 ? window.api.rsaEncrypt(JSON.stringify(data)) : '';
    const header = {
        nonce: nonce,
        timestamp,
    }
    const headersKyes = Object.keys(header).sort();
    const headersStr = parseObjectKeyValue(headersKyes, headers);

    const s = window.api.sign(headersStr + dataStr + '888');
    headers['sign'] = s;
    options.headers = headers;
    if (!!dataStr) {
        const params = {
            data: dataStr
        }
        if (options.method == 'GET') {
            options.query = params;
        } else {
            options.body = JSON.stringify(params);
        }
    }
    const res = await next(options);

    if (res.status != 200) {
        showToast(res.data.msg);
    }
    if (res.status == 401) {
        router.replace('/login');
    }
    return res;
});



export default class HttpRepositiry {
    public static login = http.post('api/users');
    public static register = http.post('api/register');
    public static getAccounts = http.get('api/accounts');
    public static pullAccount = http.get('api/accounts/pull');
    public static pushAccounts = http.post('api/accounts');
    public static resolvingAnchor = http.post('api/anchors');
    public static live = http.post('api/live');
    public static bindAnchor = http.put('api/users');
    public static getAnchor = http.get('api/users');
    public static update = http.get('api/update');
    public static online = http.get('api/online');
    public static checkStatus = http.post('api/check/status');


}
